﻿<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Drawing.Drawing2D" %>

<script runat="server">

    private string path = HttpContext.Current.Server.MapPath("/images");
    private string imgPath = "/images";

    public enum Dimensions
    {
        Width,
        Height
    }
    public enum AnchorPosition
    {
        Top,
        Center,
        Bottom,
        Left,
        Right
    }

    public System.Drawing.Image FixedSize(System.Drawing.Image imgPhoto, int Width, int Height)
    {
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0;

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)Width / (float)sourceWidth);
        nPercentH = ((float)Height / (float)sourceHeight);

        //if we have to pad the height pad both the top and the bottom
        //with the difference between the scaled height and the desired height
        if (nPercentH < nPercentW)
        {
            nPercent = nPercentH;
            destX = (int)((Width - (sourceWidth * nPercent)) / 2);
        }
        else
        {
            nPercent = nPercentW;
            destY = (int)((Height - (sourceHeight * nPercent)) / 2);
        }

        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.Clear(Color.White);
        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

        grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
            GraphicsUnit.Pixel);

        grPhoto.Dispose();
        return bmPhoto;
    }       //ok


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["del"]))
        {
            fileDel(Request.QueryString["del"]);
        }
        else if (!string.IsNullOrEmpty(Request.QueryString["fldel"]))
        {
            folderDel(Request.QueryString["fldel"]);
        }

        pageBind();
    }

    #region Function

    /// <summary>
    /// Page Load - page object bind
    /// </summary>
    private void pageBind()
    {
        lnkHome.NavigateUrl = "up.aspx";

        DirectoryInfo drInfo = new DirectoryInfo(path);

        // Main Folder
        bindFolder(drInfo);

        if (!string.IsNullOrEmpty(Request.QueryString["fl"]))
        {
            path += "\\" + Request.QueryString["fl"];

            imgPath += "/" + Request.QueryString["fl"];

            // Path Change
            drInfo = new DirectoryInfo(path);

            // Create Folder Panel  !? Next Step 
            pnlCreators.Visible = false;
        }

        // File List
        bindFile(drInfo);
    }

    /// <summary>
    /// Folder List
    /// </summary>
    /// <param name="drInfo"></param>
    private void bindFolder(DirectoryInfo drInfo)
    {
        DirectoryInfo[] drList = drInfo.GetDirectories();

        List<DirectoryInfo> lstDirectory = new List<DirectoryInfo>();

        foreach (DirectoryInfo drc in drList)
        {
            lstDirectory.Add(drc);
        }

        lvFolderList.DataSource = lstDirectory;
        lvFolderList.DataBind();
    }

    /// <summary>
    /// File List
    /// </summary>
    /// <param name="drInfo"></param>
    private void bindFile(DirectoryInfo drInfo)
    {
        FileInfo[] rgFiles = drInfo.GetFiles();

        List<FileInfo> lstFile = new List<FileInfo>();

        foreach (FileInfo fi in rgFiles)
        {
            lstFile.Add(fi);
        }

        lvFileList.DataSource = lstFile;
        lvFileList.DataBind();

    }

    #region File Delete

    private void fileDel(string fileName)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["fl"]))
        {
            File.Delete(path + "\\" + Request.QueryString["fl"] + "\\" + fileName);
        }
        else
        {
            File.Delete(path + "\\" + fileName);
        }
    }

    #endregion

    #region Folder Delete

    private void folderDel(string folder)
    {
        Directory.Delete(path + "\\" + folder, true);

        Response.Redirect("up.aspx");
    }

    #endregion

    #endregion

    #region Event

    protected void btnCreateFolder_click(object sender, EventArgs e)
    {
        if (!Directory.Exists(path + "\\" + txtFolder.Text.Trim()))
            Directory.CreateDirectory(path + "\\" + txtFolder.Text.Trim());

        pageBind();
    }

    protected void btnAddFile_click(object sender, EventArgs e)
    {
        try
        {
            string name = flUpload.FileName;
            string extend = "";
            if (!string.IsNullOrEmpty(name))
            {
                if (name.Contains('.'))
                {
                    extend = name.Substring(name.LastIndexOf('.'));
                    name = name.Substring(0, name.LastIndexOf('.'));
                }
            }

            flUpload.SaveAs(path + "\\" + flUpload.FileName);

            //System.Drawing.Image imgs = System.Drawing.Image.FromFile(path + "\\" + flUpload.FileName);

            //imgs = this.FixedSize(imgs, 100, 100);
            //imgs.Save(path + "\\" + name + "_s" + extend);
            using (System.Drawing.Image imgs = System.Drawing.Image.FromFile(path + "\\" + flUpload.FileName))
            {
                this.FixedSize(imgs, 160, 240).Save(path + "\\" + name + "_s" + extend);
                imgs.Dispose();
            }

            //Delete file source
            //Skip file thumbnail
            File.Delete(path + "\\" + name + extend);

            if (!string.IsNullOrEmpty(Request.QueryString["fl"]))
            {
                Response.Redirect("up.aspx?fl=" + Request.QueryString["fl"]);
            }
            else
            {
                Response.Redirect("up.aspx");
            }
        }
        catch (Exception ex)
        {

        }
    }


    protected void lvFileList_ItemDataBound(object sender, ListViewItemEventArgs e)
    {

        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = (ListViewDataItem)e.Item;
            System.Web.UI.WebControls.Image imgList = (System.Web.UI.WebControls.Image)e.Item.FindControl("imgList");

            imgList.ImageUrl = imgPath + "/" + ((FileInfo)dataItem.DataItem).Name;
        }
    }

    protected void lvFileList_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        //set current page startindex, max rows and rebind to false
        lvDataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);

        //rebind List View
        pageBind();
    }


    #endregion
    
    
</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>netImageBrowser</title>
    <link href="css/browser.css" rel="stylesheet" type="text/css" />
    <link href="css/jquery.contextMenu.css" rel="stylesheet" type="text/css" />
	<link rel="stylesheet" href="/Content/admin/css/style.default.css" type="text/css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>

    <script src="js/jquery.contextMenu.js" type="text/javascript"></script>

    <script src="js/jquery.jqURL.js" type="text/javascript"></script>

    <script type="text/javascript">
			
			$(document).ready( function() {
			    $('a[rel*=jmenu]').click(function () {
			        var path = "images/";
			        var queryString = $.jqURL.get("fl");

			        if (queryString != undefined || queryString != null) {
			            path += queryString + "/";
			        }

			        window.opener.document.getElementById('avarta').value = "/"+ path + $(this).attr('id'), $(this).attr('id');
			        window.opener.document.getElementById('images').src = "/"+ path + $(this).attr('id'), $(this).attr('id');
			        self.close();
			    });
				// Show menu when File is clicked
				$('a[rel*=jmenu]').contextMenu({
					menu: 'myMenu'
				},
					function(action, el, pos) {
					
				    var queryString = $.jqURL.get("fl");
				   
				   if(action == "paste"){
				   
				    var path =  "images/";
				    var queryString = $.jqURL.get("fl");
				    
				    if(queryString != undefined ||  queryString != null){
				        path += queryString+"/";
				    }

				    window.opener.document.getElementById('avarta').value = path + $(el).attr('id'), $(el).attr('id');
				    window.opener.document.getElementById('images').src = path + $(el).attr('id'), $(el).attr('id');
					self.close();

				   }// if end
				   else if(action == "delete"){
				   
				    if(queryString != null && queryString != undefined){
                            window.location= "up.aspx?fl="+queryString+"&del="+$(el).attr('id');
                        }
                        else{
                            window.location= "up.aspx?del="+$(el).attr('id');
                        }
				   }// else if end
				   
				});// contextMenu end
				
				// Show menu when Folder is clicked
				$('a[rel*=fmenu]').contextMenu({
					menu: 'myFolderMenu'
					
				},
					function(action, el, pos) {
				    
				    if(action == "delete"){
                        window.location= "up.aspx?fldel="+$(el).attr('id');
				   }//  if end
				   
				});// contextMenu end
				
			});// documentReady end
			
    </script>
   


</head>
<body>
    <form id="form1" runat="server">
    <div id="contentwrapper" class="contentwrapper nopadding">
    <div class="filemgr">
            	<div class="filemgr_left" style="float:left">
                	<div class="filemgr_head">
                    	<ul class="filemgr_menu">
                            <li class="marginleft20 filesearch" style="margin-bottom: 10px;">
                                <asp:Panel runat="server" ID="pnlCreators" Width="100%">
                                    Tạo thư mục:
                                    <asp:TextBox ID="txtFolder" runat="server" Width="300px"></asp:TextBox>
                                    <asp:Button runat="server" ID="btnCreateFolder" class="newfolder" Text="Tạo Thư mục" OnClick="btnCreateFolder_click" />
                                </asp:Panel>
                            </li>
                        	<li class="marginleft20 filesearch">
                            	<div style="width:100%">
                                	Upload File:
                                    <asp:FileUpload ID="flUpload" runat="server" />
                                    <asp:Button runat="server" class="newfilebutton radius2" ID="btnAddFile" Text="Thêm File" OnClick="btnAddFile_click" />
                                </div>
                            </li>
                        </ul>
                        <span class="clearall"></span>
                    </div><!--filemgr_head-->
                    
                    <div class="filemgr_category">
                    	<ul>
                        	 <asp:DataPager ID="lvDataPager1" runat="server" PagedControlID="lvFileList" PageSize="20" OnPagePropertiesChanging="lvFileList_PagePropertiesChanging">
                                <Fields>
                                    <asp:NextPreviousPagerField ShowFirstPageButton="True"  ShowNextPageButton="False" />
                                    <asp:NumericPagerField ButtonType="Link" />
                                    <asp:NextPreviousPagerField ShowLastPageButton="True"  ShowPreviousPageButton="False" />
                                </Fields>
                            </asp:DataPager>
                        </ul>
                    </div><!--filemgr_category-->
                    
                    <div class="filemgr_content">
						
                        <small>
                        	<strong>
                            	<em>Chọn chuột phải:"Lựa chọn" để lựa chọn ảnh bạn muốn sử dụng và "Xóa" để xóa ảnh</em>
                            </strong>
                        </small>
                        
                        <br /><br />
                    	
                        <ul class="listfile">
                            <asp:ListView runat="server" ID="lvFileList" OnItemDataBound="lvFileList_ItemDataBound">
                                <LayoutTemplate>
                                    <div id="itemPlaceholder" runat="server">
                                    </div>
                                </LayoutTemplate>
                                <ItemTemplate>
                                    <li><a id='<%# Eval("NAME") %>' rel="jmenu">
                                        <asp:Image runat="server" Width="42" Height="90" ID="imgList" />
                                    </a></li>
                                </ItemTemplate>
                            </asp:ListView>
                        </ul>
                        
                        <br clear="all" />
                        
                    </div><!--filemgr_content-->
                    
                </div><!--filemgr_left -->
                
                <div class="filemgr_right" style="float:right">
                	<div class="filemgr_rightinner">
                    	<div class="contenttitle2" style="margin-top: 0">
                            <h3>Thư mục</h3>
                        </div><!--contenttitle-->
                        <ul class="menuright">
                        	<li class="current"><asp:HyperLink runat="server" ID="lnkHome" BorderStyle="None" CssClass="Home">Thư mục ảnh upload</asp:HyperLink></li>
                           <asp:ListView runat="server" ID="lvFolderList">
                            <LayoutTemplate>
                                <div id="itemPlaceholder" runat="server">
                                </div>
                            </LayoutTemplate>
                            <ItemTemplate>
                                <li><a href='up.aspx?fl=<%# Eval("NAME") %>' rel="fmenu" id='<%# Eval("NAME") %>'>
                                    <%# Eval("NAME") %></a>
                                </li>
                            </ItemTemplate>
                        </asp:ListView>
                        </ul>
                        
                    </div><!-- filemgr_rightinner -->
                </div><!-- filemgr_right -->
                <br clear="all" />
            </div>
            
 
    <ul id="myMenu" class="contextMenu">
        <li class="paste"><a href="#paste">Lựa chọn</a></li>
        <li class="delete"><a href="#delete">Xóa</a></li>
    </ul>
    <ul id="myFolderMenu" class="contextMenu">
        <li class="delete"><a href="#delete">Xóa</a></li>
    </ul>
</div>
    </form>
</body>
</html>
